package com.chai.nfcrw;

import android.content.Intent;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Base64;
import android.view.View;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.databinding.DataBindingUtil;

import com.chai.nfcrw.databinding.ActivityMainBinding;

import java.nio.charset.StandardCharsets;

public class MainActivity extends AppCompatActivity implements NfcAdapter.ReaderCallback,
        View.OnClickListener {

    private NfcAdapter nfcAdapter;

    private ActivityMainBinding mDataBinding;

    private Tag currentTag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        mDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        initNFC();
    }


    void initNFC() {
        nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (nfcAdapter == null) {
            Toast.makeText(this, "此设备不支持NFC", Toast.LENGTH_SHORT).show();
            return;
        }

        // 检查NFC是否开启
        if (!nfcAdapter.isEnabled()) {
            Toast.makeText(this, "请先打开NFC", Toast.LENGTH_LONG).show();
            // 跳转NFC开关位置
            startActivity(new Intent(Settings.ACTION_NFC_SETTINGS));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 启用NFC读取模式，设置读取标志和回调
        if (nfcAdapter != null) {
            //ISO 14443-3A
            nfcAdapter.enableReaderMode(this, this, NfcAdapter.FLAG_READER_NFC_A, null);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 禁用NFC读取模式
        if (nfcAdapter != null) {
            nfcAdapter.disableReaderMode(this);
        }
    }

    @Override
    public void onTagDiscovered(Tag tag) {
        currentTag = tag;
        String s = NFCUtils.readNfcTagData(tag);
        mDataBinding.tvRead.setText(s);
    }

    @Override
    public void onClick(View v) {
        if (v == mDataBinding.btnExecutionWrite) {
            boolean b = NFCUtils.writeDataToNfcTag(mDataBinding.etWrite.getText().toString(), currentTag);
            mDataBinding.btnExecutionWrite.setText(b ? "写入成功" : "写入失败");
        } else if (v == mDataBinding.btnExecutionWriteBash64) {
            String string = mDataBinding.etWrite.getText().toString();

            //解析编码base64解码
            byte[] encodedBytes = Base64.encode(string.getBytes(StandardCharsets.UTF_8), Base64.DEFAULT);
            String s = new String(encodedBytes);
            boolean b = NFCUtils.writeDataToNfcTag(s,currentTag);
            mDataBinding.btnExecutionWriteBash64.setText(b ? "写入成功" : "写入失败");
        } else if (v == mDataBinding.btnExecutionWriteStartApp) {
            boolean b = NFCUtils.writeAppLaunchUriToNfcTag(currentTag, mDataBinding.etWriteStartApp.getText().toString());
            mDataBinding.btnExecutionWriteStartApp.setText(b ? "写入成功" : "写入失败");
        } else if (v == mDataBinding.btnExecutionWriteAddress) {
            boolean b = NFCUtils.writeAddressToNfcTag(currentTag,
                    mDataBinding.longitude.getText().toString(),
                    mDataBinding.latitude.getText().toString(),
                    mDataBinding.address.getText().toString()
            );
            mDataBinding.btnExecutionWriteAddress.setText(b ? "写入成功" : "写入失败");
        } else if (v == mDataBinding.btnExecutionWriteUrl) {
            boolean b = NFCUtils.writeUrlToNfcTag(currentTag, mDataBinding.etWriteUrl.getText().toString());
            mDataBinding.btnExecutionWriteUrl.setText(b ? "写入成功" : "写入失败");
        }
    }

}